// JavaScript Document

//Cargar listado de eventos monitoreados
	var monitorEventListTemp = new Array(); //listado de eventos monitoreados
	var lastIdWeb = 0;
	var lastIdByk = 0;
	var lastReqParams = '';

	var eventLimit = 50; //cantidad maxima de eventos a mostrar por lote
	var eventLotes = 1; //cantidad de lotes de eventos a mostrar
	var eventCountPrinted = 0; //cantidad de eventos impresos

    var reqHandlerMonitor = null;

	var reqHandlerMonitorLeerEvento = null;

	var modalMarcarEvento = null; //popup modal para marcar eventos

	var eventosSeleccionadosWEBId = new Array();
	var eventosSeleccionadosBYKId = new Array();

	function checkedEventoMonitor(check, esWeb){
		if (check.checked)
			if(parseInt(esWeb)==1)
				eventosSeleccionadosWEBId.push(check.value);
			else
				eventosSeleccionadosBYKId.push(check.value);
		else {
			if(parseInt(esWeb)==1){
				pos=indexOfArray(eventosSeleccionadosWEBId,check.value.toString());
				if (pos!=-1)
				    eventosSeleccionadosWEBId.splice(pos,1);
				}
			else {
				pos=indexOfArray(eventosSeleccionadosBYKId,check.value.toString());
				if (pos!=-1)
				    eventosSeleccionadosBYKId.splice(pos,1);
				}
			}
	}

	function printEventMonitor(){
		for (var i=0; i<monitorEventListTemp.length; i++) {
			var eventLine = '<div id="eventLine'+monitorEventListTemp[i].id+'_'+monitorEventListTemp[i].tipoWeb+'" style="width:98%; background:#F1F1F1; margin:2px;"';
			if ((monitorEventListTemp[i].datos!='')&&(monitorEventListTemp[i].datos!=null))
				eventLine += 'onmouseover="this.style.background=\'#FDFCFB\'; Tip(\''+monitorEventListTemp[i].datos+'\', SHADOW, true);" onmouseout="this.style.background=\'#F1F1F1\'; UnTip();">';
			else
				eventLine += 'onmouseover="this.style.background=\'#FDFCFB\'" onmouseout="this.style.background=\'#F1F1F1\'" >';
			eventLine += '<input type="checkbox" name="boxEventos[]" value="'+monitorEventListTemp[i].id+'"  onClick="checkedEventoMonitor(this,'+monitorEventListTemp[i].tipoWeb+');" >';
			eventLine += '<span class="inputLBL">'+monitorEventListTemp[i].fecha+'</span>';
        	eventLine += ' -- ';
        	var vehiculoActual = misVehiculosHash.get(monitorEventListTemp[i].cuentaId);
        	var movilTXT = vehiculoActual.marca + ' ' + vehiculoActual.modelo + ' ' + vehiculoActual.patente;
	        eventLine += ' <span class="inputLBL">' + movilTXT + '</span>';
			eventLine += ' -- ';
	        eventLine += ' <span class="inputLBL">'+monitorEventListTemp[i].detalle+'</span>';
			eventLine += '<img src="images/readItemImg.gif" width="16" height="16" border="0" style="cursor:pointer;" onclick="openPopUpLeerEventoMonitor('+monitorEventListTemp[i].id+','+monitorEventListTemp[i].tipoWeb+');" title="Procesar este evento"/> ';
	        eventLine += '<img src="images/comandosItemImg.gif" width="16" height="16" border="0" style="cursor:pointer;" onclick="cleanAllStates(); AccordionMenu.openPanelNumber(0); centroDeComandos('+monitorEventListTemp[i].cuentaId+');" title="Enviar Comando"/> ';
			eventLine += '</div>';
			document.getElementById('divMonitorList').innerHTML += eventLine;
			}
		monitorEventListTemp.length=0;
	}


	function refreshViewMonitor(){
		if ((lastIdWeb!=0)||(lastIdByk!=0)){
			if (document.getElementById('eventsListNoResult')!=null)
				document.getElementById('divMonitorList').removeChild(document.getElementById('eventsListNoResult'));
		 	printEventMonitor();
			if(!monitorActivoFlag)
				sideMonitor.alertar(true);
			}
		else{
			document.getElementById('divMonitorList').innerHTML = '<div id="eventsListNoResult"><span class="inputLBL">No se encontraron eventos registrados para el filtro aplicado.</span></div>';
		}
	}

	function OnReadyStateChangeMonitor(){
		ready = reqHandlerMonitor.readyState;
		if (ready == READY_STATE_COMPLETE) {
			eventosJSON =  reqHandlerMonitor.responseText.parseJSON();
			//document.getElementById('divMonitorList').innerHTML = reqParams +' | '+eventosJSON;
			if (eventosJSON.length != 'undefined') {
				for(var i=0; i < eventosJSON.length; i++){
					if (parseInt(eventosJSON[i].tipoWeb)==1)
						lastIdWeb = eventosJSON[i].id;
					else
						lastIdByk = eventosJSON[i].id;
					monitorEventListTemp.push(eventosJSON[i]);
					}
				eventCountPrinted+=eventosJSON.length;
				refreshViewMonitor();
			}
		document.getElementById("busyImg").style.visibility = "hidden";
		autoRefreshFlag = 0;
		}
	}

	function CargarEventosMonitor() {

		if(lastReqParams!=reqParams){
			lastReqParams=reqParams;
			eventCountPrinted = 0;
			eventLotes = 1;
			lastIdWeb = 0;
	        lastIdByk = 0;
			document.getElementById('divMonitorList').innerHTML = '';
		}
		if(eventCountPrinted < eventLimit*eventLotes){
			countEvents = (eventLimit*eventLotes)-eventCountPrinted;
    		reqParamsEventosMoni = "COMMAND=MONITOR";
    		reqParamsEventosMoni += "&" + reqParams;
			reqParamsEventosMoni += "&UNIQUEID="+UNIQUE_ID;
			reqParamsEventosMoni += "&ESFLOTA="+((OBJETIVO==3)?"1":"0");
			reqParamsEventosMoni += "&LASTIDWEB=" + lastIdWeb;
			reqParamsEventosMoni += "&LASTIDBYK=" + lastIdByk;
			reqParamsEventosMoni += "&LIMIT=" + countEvents;
	    	document.getElementById("busyImg").style.visibility = "visible";
    		if (msie)
        	    reqHandlerMonitor = new ActiveXObject("Microsoft.XMLHTTP");
	        else
    	        reqHandlerMonitor = new XMLHttpRequest();
        	reqHandlerMonitor.onreadystatechange = OnReadyStateChangeMonitor;
	        reqHandlerMonitor.open("POST", "querycontroller.php", true);
    	    reqHandlerMonitor.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			reqHandlerMonitor.send(reqParamsEventosMoni);
			}

    }

	function OnReadyStateChangeMonitorLeerEvento(){
		ready = reqHandlerMonitorLeerEvento.readyState;
		if (ready == READY_STATE_COMPLETE) {
			document.getElementById("busyImgEventoMonitor").style.visibility = "hidden";
			leerEventoJSON =  reqHandlerMonitorLeerEvento.responseText.parseJSON();

			document.getElementById('readEventoErrorDisplay').innerHTML = leerEventoJSON;
			showDiv('readEventoErrorDisplay');
			if (leerEventoJSON != false) {
				if(modalMarcarEvento!=null)
					modalMarcarEvento.hide();
				//ahora elimino el evento de la lista si es que fue procesado
				if (parseInt(eventosLeerProcess)===1){
					var eventsArray = new Array();
					var divEventsList = document.getElementById('divMonitorList');
					if (trim(eventosLeerIdsWeb)!='')
						eventsArray = eventosLeerIdsWeb.split(",");
					for (var i=0; i<eventsArray.length; i++){
						var idEventLine="eventLine"+eventsArray[i]+'_1';
						var olddiv = document.getElementById(idEventLine);
  						divEventsList.removeChild(olddiv);
					}
					eventCountPrinted-=eventsArray.length;
					eventsArray = new Array();
					if (trim(eventosLeerIdsByk)!='')
						eventsArray = eventosLeerIdsByk.split(",");
					for (var i=0; i<eventsArray.length; i++){
						var idEventLine="eventLine"+eventsArray[i]+'_0';
						var olddiv = document.getElementById(idEventLine);
  						divEventsList.removeChild(olddiv);
					}
					eventCountPrinted-=eventsArray.length;
					eventosSeleccionadosWEBId = new Array();
					eventosSeleccionadosBYKId = new Array();
				}
			}
			else {
				document.getElementById('readEventoErrorDisplay').innerHTML = "El evento no pudo ser procesado por problemas de conexion a la DB";
				showDiv('readEventoErrorDisplay');
			}
		}
	}

	//variables globales
	var eventosLeerIdsWeb;
	var eventosLeerIdsByk;
	var eventosLeerProcess;
	function LeerEventoMonitor(idsWeb, idsByk, process, msg) {
    if (monitorActivoFlag){
		eventosLeerIdsWeb = idsWeb;
		eventosLeerIdsByk = idsByk;
		eventosLeerProcess = process;
    	reqParamsEventosMoniLeer = "COMMAND=PROCESAREVENTO";
		reqParamsEventosMoniLeer += "&IDEVENTOSWC=" + idsWeb;
		reqParamsEventosMoniLeer += "&IDEVENTOSBY=" + idsByk;
		reqParamsEventosMoniLeer += "&PROCESADO=" + process;
		reqParamsEventosMoniLeer += "&DATOS=" + msg;
	    document.getElementById("busyImgEventoMonitor").style.visibility = "visible";
    	if (msie)
            reqHandlerMonitorLeerEvento = new ActiveXObject("Microsoft.XMLHTTP");
	    else
    	    reqHandlerMonitorLeerEvento = new XMLHttpRequest();
        reqHandlerMonitorLeerEvento.onreadystatechange = OnReadyStateChangeMonitorLeerEvento;
	    reqHandlerMonitorLeerEvento.open("POST", "persistireventomoni.php", true);
    	reqHandlerMonitorLeerEvento.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		reqHandlerMonitorLeerEvento.send(reqParamsEventosMoniLeer);
		}
    }

	function generateHtmlPopUpEventoMonitor(callProcess,callNoProcess){
		var HTMLcontent = '<table border="0" width="275">';
		HTMLcontent += '<tr>';
        HTMLcontent += ' <td colspan="2">';
        HTMLcontent += '  <div id="readEventoErrorDisplay" class="errorDisplay" style="display:none"></div>';
        HTMLcontent += ' </td>';
      	HTMLcontent += '</tr>';
		HTMLcontent += '<tr>';
      	HTMLcontent += '<tr>';
        HTMLcontent += ' <td valign="top">';
        HTMLcontent += '  <span class="inputLBL">Descripcion</span>';
        HTMLcontent += ' </td>';
		HTMLcontent += ' <td valign="top" align="right">';
        HTMLcontent += '  <img id="busyImgEventoMonitor" src="imagenes/loader_pulse.gif" style="display:none;">';
        HTMLcontent += ' </td>';
        HTMLcontent += '</tr>';
        HTMLcontent += '<tr>';
        HTMLcontent += ' <td colspan="2">';
        HTMLcontent += '  <textarea name="eventoDescProcesar" id="eventoDescProcesar" cols="40" rows="3" class="gmapInputText"></textarea>';
        HTMLcontent += ' </td>';
      	HTMLcontent += '</tr>';
		HTMLcontent += '<tr>';
        HTMLcontent += ' <td colspan="2">';
		HTMLcontent += '  <a onclick="'+callProcess+'"><span class="linked">marcar evento/s como procesado</span></a>';
        HTMLcontent += ' </td>';
      	HTMLcontent += '</tr>';
		HTMLcontent += '<tr>';
        HTMLcontent += ' <td colspan="2">';
        HTMLcontent += '  <a onclick="'+callNoProcess+'"><span class="linked">guardar descripcion sin marcar como procesado/s</span></a>';
        HTMLcontent += ' </td>';
      	HTMLcontent += '</tr>';
    	HTMLcontent +='</table>';
		return HTMLcontent;
	}

	function openPopUpLeerEventoMonitor(ids,esWeb){
		var callProcess='LeerEventoMonitor(';
		var callNoProcess='LeerEventoMonitor(';
		if (parseInt(esWeb)==1){
			callProcess +='\''+ids+'\',\'\',1,document.getElementById(\'eventoDescProcesar\').value);';
			callNoProcess +='\''+ids+'\',\'\',0,document.getElementById(\'eventoDescProcesar\').value);';
		}
		else{
			callProcess += '\'\',\''+ids+'\',1,document.getElementById(\'eventoDescProcesar\').value);';
			callNoProcess += '\'\',\''+ids+'\',0,document.getElementById(\'eventoDescProcesar\').value);';
		}

		var HTMLcontent = generateHtmlPopUpEventoMonitor(callProcess,callNoProcess);

		modalMarcarEvento = dhtmlmodal.open('modalMarcarEvento', 'inline', HTMLcontent, 'Procesar evento', 'width=310px,height=200px,resize=0,scrolling=0,center=1');
	}

	function openPopUpLeerEventosSelected(){
		if ((eventosSeleccionadosWEBId.length>0)||(eventosSeleccionadosBYKId.length>0)){
			var callProcess='LeerEventoMonitor(';
			var callNoProcess='LeerEventoMonitor(';
			var idsWeb = '';
			var idsByk = '';
			if (eventosSeleccionadosWEBId.length>0) idsWeb = eventosSeleccionadosWEBId.toString();
			if (eventosSeleccionadosBYKId.length>0) idsByk = eventosSeleccionadosBYKId.toString();

			callProcess +='\''+idsWeb+'\',\''+idsByk+'\',1,document.getElementById(\'eventoDescProcesar\').value);';
			callNoProcess +='\''+idsWeb+'\',\''+idsByk+'\',0,document.getElementById(\'eventoDescProcesar\').value);';

			var HTMLcontent = generateHtmlPopUpEventoMonitor(callProcess,callNoProcess);

			modalMarcarEvento = dhtmlmodal.open('modalMarcarEvento', 'inline', HTMLcontent, 'Procesar evento', 'width=310px,height=200px,resize=0,scrolling=0,center=1');
			}
		else alert('Debe seleccionar al menos un evento de la lista para realizar esta operacion');
	}